/**
 * 小镇里有n个人，按从1到n的顺序编号，传言称，这些人中有一个暗地里是小镇法官，如果小镇法官真的存在，那么
 * 1. 小镇法官不会相信任何人
 * 2. 每个人（除了小镇法官）都信任这位小镇法官
 * 3. 只有一个人满足属性1和属性2
 * 给你一个数组trust, 其中trust[i] = [ai, bi]表示编号为ai的人信任编号为bi的人，如果小镇法官存在并且可以确定他的身份，
 * 请返回该法官的编号；否则，返回-1
 * 示例1: 
 *  输入: n = 2, trust = [["小美", "小团"]]
 *  输出: "小团"
 * 示例2:
 *  输入: n = 3, trust = [["小美", "小阿"], ["小团", "小阿"]]
 *  输出: "小阿"
 * 示例3:
 *  输入: n = 3, trust = [["小美", "小阿"], ["小团", "小阿"], ["小阿", "小美"]]
 *  输出: -1
*/

function findJudge (n, trust) {
    const target = [];
    // 建立一个关于入度和出度的数组
    const graph = {};
    const trustFlat = [];
    for (let i = 0; i < trust.length; i++) {
       trustFlat.push(...trustFlat.concat(trust[i]));
    }
    for (let i = 0; i < trustFlat.length; i++) {
        if (!graph[trustFlat[i]]) {
            graph[trustFlat[i]] = {
                in: 0,
                out: 0
            }
        }
    }
    // 遍历信任关系表
    for (let i = 0; i < trust.length; i++) {
        const [a, b] = trust[i];
        graph[a].out++;
        graph[b].in++;
    }
    // 找到入度为人数，出度为0的数据并返回其下标
    for (let key in graph) {
        if (graph[key].out === 0 && graph[key].in === n - 1) {
            target.push(key)
        }
    }
    if (target.length === 1) {
        return target[0]
    } else {
        return -1
    }
}
console.log(findJudge(2, [["小美", "小团"]]));
console.log(findJudge(3, [["小美", "小阿"], ["小团", "小阿"]]));
console.log(findJudge(3, [["小美", "小阿"], ["小团", "小阿"], ["小阿", "小美"]]));
